package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import db.MessageDAO;

public class ConnectionHandler implements Runnable {
	private boolean isStopped = false;
	private ExecutorService pool;
	private ServerSocket server;
	private MessageDAO db;
	private PerformanceMeasure pm;
	
	/**
	 * This thread creates a new connection thread for every new connection that
	 * is made with the server socket
	 */
	public ConnectionHandler(int  portNumber, MessageDAO db) {
		pool = Executors.newFixedThreadPool(150);
		this.db = db;
		try {
			server = new ServerSocket(portNumber);
		}
		catch (UnknownHostException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		pm = new PerformanceMeasure();
		pm.start();
		while (!isStopped()) {
			try {
				// Listens to new connections and starts a new thread
				pool.execute(new Connection(server.accept(), db));
			}
			catch (IOException e) {
				if (isStopped()) {
                    break;
                }
				else {
                	e.printStackTrace();                	
                }             
			}
		}
		pool.shutdown();
	}
	
	private synchronized boolean isStopped() {
        return isStopped;
    }
	
	/**
	 * Closes the server socket and stops the ConnectionHandler thread
	 */
	public synchronized void close(){
        isStopped = true;
        pm.close();
        try {
        	server.close();
        	
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}